#include "Game.h"

IGame* createGame( HINSTANCE hInst, HWND hWnd )
{
	return new Game( hInst, hWnd );
}

Game::Game( HINSTANCE hInst, HWND hWnd ) :
	m_input( hInst, hWnd ), m_convexSet( 0 )
{
	// initialize camera
	m_camera.hand = Camera::RIGHTHANDED;

	m_camera.eye = float3( 0, 0, 20.f );
	m_camera.at  = float3( 0, 0, 0 );
	m_camera.up  = float3( 0, 1, 0 );

	m_camera.projectionType = Camera::PERSPECTIVE_FOV;
	m_camera.perspectiveFov.fovy = D3DXToRadian(45.f);
	m_camera.perspectiveFov.aspect = 1024.f/768.f;

	m_camera.zn = 1.0f;
	m_camera.zf = 100.0f;

	// initialize polygon
	m_concave.push_back( float3( 0, 0, 0 ) );
	m_concave.push_back( float3( 2, 0, 0 ) );
	m_concave.push_back( float3( 0, 2, 0 ) );
	m_concave.push_back( float3( .5f, .5f, 0 ) );
	m_concave.push_back( float3( -.5f, .5f, 0 ) );

	// initialize convex set
	m_convexSet.reset( new ConvexSet( m_concave ) );

	// initialize polygon list
	m_polygons = m_convexSet->polygonList();

	// initialize colors
	m_colors[0] = float4(1.f, 1.f, 0.2f, 0.2f);
	m_colors[1] = float4(1.f, 0.2f, 1.f, 0.2f);
	m_colors[2] = float4(1.f, 0.2f, 0.2f, 1.f);
	m_colors[3] = float4(1.f, 0.4f, 0.4f, 0.4f);
}

Game::~Game()
{
	m_polygonView.destroy();
	m_d3dDevice = 0;
}

void Game::onCreateGraphics( D3DDevice device )
{
	m_d3dDevice = device;
	m_polygonView.initialize( m_d3dDevice );

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 world = identity44();
	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_WORLD, &world );
	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
	
}

void Game::onResetGraphics( D3DDevice device )
{
	//TODO: Add code to handle lost device ( resizing issue )

	m_d3dDevice = device;

	m_polygonView.destroy();
	m_polygonView.initialize( m_d3dDevice );

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onLostGraphics()
{
}

void Game::onFrameMove(float dt)
{
}

void Game::onFrameRender(float dt)
{
	for( int i = 0; i < m_polygons.size(); i++ )
	{
		m_polygonView.setup( m_polygons[i], m_colors[i%(sizeof(m_colors)/sizeof(float4))] );
		float44 world = identity44();
		m_polygonView.render( world );
	}
}

void Game::onDestroyGraphics()
{
}
